import os
import sys
from loguru import logger


class Loggers:
    def __init__(self, log_dir='logs', level='INFO'):
        self.directory = log_dir

        if not os.path.exists(self.directory):
            os.makedirs(self.directory)

        # 获取主程序文件名
        filename = os.path.splitext(os.path.basename(sys.argv[0]))[0] + '.log'
        log_file_path = os.path.join(self.directory, filename)

        logger.remove()
        # 自定义颜色
        levels = {
            "DEBUG": "<blue>",
            "INFO": "<green><bold>",
            "WARNING": "<magenta>",
            "ERROR": "<red>",
            "CRITICAL": "<red><bold>"
        }

        for log_level, color in levels.items():
            logger.level(log_level, color=color)

        logger.add(
            sys.stderr,
            level=level,
            format="<yellow><bold>{time:YYYY-MM-DD HH:mm:ss}</bold></yellow> | <level>{level}</level> | "
                   "<level>{file}:{function}:{line}</level> - <cyan><bold>{message}</bold></cyan>",
            colorize=True
        )

        logger.add(
            log_file_path.split('.log')[0] + "_{time:YYYY-MM-DD}.log",
            level="DEBUG",  # 记录所有级别的日志
            rotation="3 days",  # 每 5 分钟轮换日志文件
            retention="3 days",  # 保留最近 5 分钟的日志文件，删除超过的日志
            encoding='utf-8',
            format="{time:YYYY-MM-DD HH:mm:ss} | {level:<8} | {file.name}:{function}:{line} - {message}"
        )
        self.logger = logger
